package com.offcn.webui.controller;

import com.alibaba.fastjson.JSON;
import com.offcn.dycommon.response.AppResponse;
import com.offcn.webui.service.ProjectServiceFeign;
import com.offcn.webui.service.UserServiceFeign;
import com.offcn.webui.vo.resp.ProjectVo;
import com.offcn.webui.vo.resp.UserRespVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Auther: yao
 * @Date: 2020/10/28 09:25
 * @Description:
 */
@Controller
public class DispathcherController {

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectServiceFeign projectServiceFeign;


    @RequestMapping("/")
    public String index(Model model) {
        //1.从缓存中读取数据
        String projectStr = redisTemplate.opsForValue().get("projectStr");
        List<ProjectVo> projectVoList = JSON.parseArray(projectStr, ProjectVo.class);
        //2.如果缓存中数据为空，则查询后台数据
        if (CollectionUtils.isEmpty(projectVoList)) {
            AppResponse<List<ProjectVo>> response = projectServiceFeign.findAllProject();
            projectVoList = response.getData();
            //3.将并重新保存到缓存中
            String newProjectStr = JSON.toJSONString(projectVoList);
            redisTemplate.opsForValue().set("projectStr", newProjectStr);
        }
        //4.得到的数据展示
        model.addAttribute("projectList", projectVoList);
        return "index";
    }


    @RequestMapping("/doLogin")
    public String doLogin(String loginacct, String password, HttpSession session) {
        //1.调用登录方法验证登录
        AppResponse<UserRespVo> response = userServiceFeign.login(loginacct, password);
        UserRespVo userRespVo = response.getData();
        if (userRespVo == null) {
            //登录失败，重新跳转到登录页  资源重定向
            return "redirect:/login.html";
        }
        //2.如果登录成功则跳转到首页，并将用户信息设置到session中
        session.setAttribute("sessionMember", userRespVo);
        //需要判断session中是否有之前登录的页面
        String preUrl = (String) session.getAttribute("preUrl");
        if (StringUtils.isEmpty(preUrl)) {
            return "redirect:/";
        }
        return "redirect:/" + preUrl;
    }



}